package com.hy.wsroom.handler;

import com.hy.wsroom.entity.Client;
import com.hy.wsroom.entity.Message;
import com.hy.wsroom.util.ClientHolder;
import com.hy.wsroom.util.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.nio.ByteBuffer;
import java.util.Objects;

import static com.hy.wsroom.constans.GlobalConstans.CLIENT_ID;

@Component
@RequiredArgsConstructor
public class WebSocketHandler extends AbstractWebSocketHandler {
    private final MessageHandlerManager messageHandlerManager;
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        super.handleBinaryMessage(session, message);
        ByteBuffer payload = message.getPayload();
        if (payload.hasArray()) {
            byte[] bytes = payload.array();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Message msg = JSONUtil.toBean(message.getPayload(), Message.class);
        assert msg != null;
        msg.setFrom(ClientHolder.getClientId());
        msg.setFromClient(ClientHolder.get());
        ClientHolder.updateLastActiveTime();
        messageHandlerManager.handle(msg);
    }

    /**
     * 连接建立
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        String clientId = (String)session.getAttributes().get(CLIENT_ID);
        Client client = new Client();
        client.setId(clientId);
        client.setSession(session);
        ClientHolder.set(client);
    }

    /**
     * 连接关闭
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        ClientHolder.remove();
    }
}
